var PeopleMedia = PeopleMedia || {};
PeopleMedia.ProfileEdit = new function () {
    this.init = function () {
        PeopleMedia.ProfileEdit.AnimateCompletionBarWidths();
        $jq('div[data-key] > div:first-child').attr('title', 'Click to Edit').on('click', PeopleMedia.ProfileEdit.ShowEditor);
        $jq('div.data > div:last-child').on('click', function (e) {
            if (e.target == this) {
                $jq(this).find('>div:last-child > a:last-child').trigger('click');
            }
        });
       

        $jq('div.messageideas > div.save > a:nth-child(1)').click(PeopleMedia.ProfileEdit.DeselectMessageIdeas);
        $jq('div.messageideas > div.save > a:nth-child(2)').click(PeopleMedia.ProfileEdit.SaveMessageIdeas);
        //$jq('div.messageideas > div.save > a:nth-child(2)').click(function(){
        //  alert("ABC");
          //PeopleMedia.ProfileEdit.SaveMessageIdeas
        //});
        $jq('div.messageideas > div.save > a:nth-child(3)').click(PeopleMedia.ProfileEdit.CancelMessageIdeas);

        $jq('.aboutmeclick').click(function () {
            $jq("#AboutMe").show();
            $jq("#AboutMyMatch").hide();
        });

        $jq('.aboutmymatchclick').click(function () {
            $jq("#AboutMe").hide();
            $jq("#AboutMyMatch").show();
        });

        PeopleMedia.ProfileEdit.ConfigureGreetingLengths();
        PeopleMedia.ProfileEdit.ConfigureMiniEssayLengths();
        PeopleMedia.ProfileEdit.ConfigurePetCheckboxes();
        PeopleMedia.ProfileEdit.ConfigureRelationshipCheckboxes();
        PeopleMedia.ProfileEdit.ConfigureDynamicAnyCheckboxes();
        PeopleMedia.ProfileEdit.ConfigureMessageIdeas();
        var focus = $jq.bbq.getState('focus');
        if (focus && focus != '') {
            $jq('div[data-key=\'' + focus + '\'] > div:first-child').click();
        }
        $jq('.lt-ie8 div.profileedit div.tabcontent > div.left > div:nth-child(2)').css('min-height', '63px');
    };
    this.ConfigureMessageIdeas = function () {
        var $allboxes = $jq('div.messageideas input[type=checkbox]');
        $allboxes.on('change', function () {
            var thisBox = $jq(this);
            if ($allboxes.filter(':checked').length > 4) {
                thisBox.attr('checked', false);
                $jq('div.messageideas div.error').show();
            } else {
                $jq('div.messageideas div.error').hide();
            }
        });
    };
    this.MaximumGreetingLengths = 1250;
    this.ConfigureGreetingLengths = function () {
        var textAreas = $jq('div.greetings textarea');
        textAreas.off('keyup focus');
        textAreas.on('keyup focus', function () {
            var limit = PeopleMedia.ProfileEdit.MaximumGreetingLengths;
            var $ta = $jq(this);
            var text = $jq.trim($ta.val());
            var textWithoutDoubleSpaces = text.replace(/ +(?= )/g, '');
            var textWithoutDoubleNewlines = textWithoutDoubleSpaces.replace(/\n+(?=\n)/g, '');
            var chars = textWithoutDoubleNewlines.length;
            if (chars > limit) {
                var new_text = text.substr(0, limit);
                $ta.val(new_text);
            }
            var remain = limit - chars;
            if (remain <= 0) {
                remain = 0;
            }

            $ta.parent().find('p.remainingcharacters span').html(remain);

        });
    };
    this.MinimumMiniEssayLengths = 100;
    this.MaximumMiniEssayLengths = 500;
    this.ConfigureMiniEssayLengths = function () {
        var textAreas = $jq('div.editminiessay textarea');
        textAreas.off('keyup focus');
        textAreas.on('keyup focus', function () {
            var limit = PeopleMedia.ProfileEdit.MaximumMiniEssayLengths;
            var $ta = $jq(this);
            var text = $jq.trim($ta.val());
            var textWithoutDoubleSpaces = text.replace(/ +(?= )/g, '');
            var textWithoutDoubleNewlines = textWithoutDoubleSpaces.replace(/\n+(?=\n)/g, '');
            var chars = textWithoutDoubleNewlines.length;
            if (chars > limit) {
                var new_text = text.substr(0, limit);
                $ta.val(new_text);
            }
            var remain = limit - chars;
            if (remain <= 0) {
                remain = 0;
            }

            $ta.parent().find('p.remainingcharacters span').html(remain);

        });
    };
    this.AnimateCompletionBarWidths = function () {
        $jq('p[data-completion-key]').each(function () {
            var $p = $jq(this);
            var key = $p.data('completion-key');
            var adjustment = 1.42;
            if (key != 'global') {
                adjustment = 1.12;
            }
            var completion = parseInt($p.data('completion-percent'), 10);
            var width = completion * adjustment + 1;
            $p.parent().animate({ width: width + 'px' }, 'slow', 'swing');
        });
    };
    this.ShowEditor = function (e) {
        var $it = $jq(this);
        var link = $it.parent().data('link');
        if (link != undefined && link != '') {
            window.location.href = link;
            return;
        }

        PeopleMedia.ProfileEdit.CancelEdit(e);
        var editSection = $it.parent().find('> div:last-child');
        var mainSection = $it.parent().find('> div:first-child');
        mainSection.addClass('whiteout');
        editSection.show();
        editSection.find('textarea').first().focus();
        editSection.find('input').first().focus();
        editSection.find('select').first().focus();
        var key = $it.parent().data('key');
        PeopleMedia.ProfileEdit.lastItemEdited = { key: key , data: PeopleMedia.ProfileEdit.GetBetterClone(editSection) };
        var buttons = $it.parent().find('> div:last-child > div:last-child');
        editSection.find('select').each(function () {
            var sel = $jq(this);
            if (sel.val() != "-1") {
                sel.find('option[value="-1"]').remove();
            }
        });
        if (key == "Height") {
            $jq('[data-key=\'Height\'] select').off('change').on('change', function () {
                var newVal = $jq(this).val();
                $jq('[data-key=\'Height\'] select').val(newVal);
            });
        }
        buttons.html('');
        var cancelButton = $jq('<a href="#cancel">Cancel</a>');
        var submitButton = $jq('<a href="#save" class="button_style">Save</a>');
        cancelButton.on('click', PeopleMedia.ProfileEdit.CancelEdit);
        submitButton.on('click', PeopleMedia.ProfileEdit.SaveEdit);
        buttons.append(submitButton);
        buttons.append(cancelButton);
    };
    this.GetBetterClone = function (obj) {
        var clone = obj.clone();
        obj.find('textarea').each(function () {
            var input = $jq(this);
            clone.find('textarea[id="' + input.attr('id') + '"]').html(input.val());
        });
        obj.find('select').each(function () {
            var input = $jq(this);
            clone.find('select[id="' + input.attr('id') + '"] > option').removeAttr('selected');
            clone.find('select[id="' + input.attr('id') + '"] > option[value="' + input.val() + '"]').attr('selected', true);
        });
        obj.find('input[type=checkbox]').each(function () {
            var box = $jq(this);
            clone.find('input[type=checkbox][value="' + box.val() + '"]').attr('checked', box.is(':checked'));
        });

        return clone;
    };
    this.SaveEdit = function (e) {        
        e.preventDefault();
        var $container = $jq(this).parent().parent().parent();
        var $errorContainer = $jq(this).parent().parent(); // used for mini-essays
        var questionKey = $container.data('key');
        var isQuestion = $container.data('question');
        if(isQuestion === undefined)
          isQuestion = false;
        var $responseGroups = $container.find('div.AllGroups > div.OptionGroup');
        var responseKeys = [];
        var responseValues = [];
        PeopleMedia.ProfileEdit.PreSaveEvents(questionKey);
        $container.addClass('saving');
        $responseGroups.each(function () {
            var $group = $jq(this);
            var key = $group.data('responsegroup-key');
            if (key == undefined || key == '') return;
            PeopleMedia.ProfileEdit.AddResponses(responseKeys, responseValues, key, $group);
        });

        if (questionKey.indexOf('miniessay') >= 0 && responseValues[0].length > 0 && responseValues[0].length < PeopleMedia.ProfileEdit.MinimumMiniEssayLengths) {
            $errorContainer.find(".miniessayerrorplace").show();
            $container.removeClass('saving');
        }
        else
        {
            $errorContainer.find(".miniessayerrorplace").hide();
            PeopleMedia.ProfileEdit.lastItemEdited = null;
            
            $jq.ajax({
                traditional: true,
                url: FRONT_SITE_URL+'user/profile/process',
                type: 'GET',
                data: {
                    SkipCSSVerif: 'HTMLEditor',
                    QuestionKey: questionKey,
                    ResponseKeys: responseKeys,
                    ResponseValues: responseValues,
                    isQuestion: isQuestion
                },
                success: PeopleMedia.ProfileEdit.SaveEditComplete,
                error: function () {
                    PeopleMedia.ProfileEdit.SaveErrorEvents(questionKey);
                },
                complete: function () {
                    $container.removeClass('saving');
                },

                dataType: 'json'
            });
          
            PeopleMedia.ProfileEdit.HideEditors(e);
        }
    };
    this.PreSaveEvents = function (key) {
        if (key.indexOf('greeting') >= 0) {
            $jq('div.greetings > h4').show();
        }
    };
    this.SaveCompleteEvents = function (key) {
        if (key.indexOf('greeting') >= 0) {
            PeopleMedia.ProfileEdit.ToggleGreetingHighlight(key);
        }
    };
    this.SaveErrorEvents = function (key) {
    };

    this.SaveEditComplete = function (response) {
		if (response.redirect) {
            location.href = response.redirect;
            return;
        }
        if (response && response.Status == "Success") {
            var $container = $jq('div[data-key=\'' + response.data.key + '\']');
            $container.find('> div:first-child').fadeOut('fast', function () { $jq(this).html(response.data.formattedResponse).fadeIn('fast'); });
            PeopleMedia.ProfileEdit.UpdateCompletion(response.data.completionData);
            $jq('div.saved').text('Saved!').fadeIn('fast').delay(2000).fadeOut('fast');
            PeopleMedia.ProfileEdit.SaveCompleteEvents(response.data.key);
        } else if (response.Message) {
            PeopleMedia.Popups.ShowGenericMessage(response.Message);
        } else {
            $jq('div.saved').text('Error Saving').fadeIn('fast').delay(2000).fadeOut('fast');
        }
        if (response && response.RequiresRefresh) {
            location.reload();
            return;
        }
        //PeopleMedia.ReloadAds();
    };
    this.UpdateCompletion = function (completionData) {
        var $comps = $jq('p[data-completion-key]');
        for (var i = 0; i < completionData.length; i++) {
            var match = $comps.filter('p[data-completion-key="' + completionData[i].key + '"]');
            match.data('completion-percent', completionData[i].value);
            match.text(completionData[i].value + '%');
        }
        PeopleMedia.ProfileEdit.AnimateCompletionBarWidths();
    };
    this.CancelEdit = function (e) {
        e.preventDefault();
        
        if (PeopleMedia.ProfileEdit.lastItemEdited != null) {
            var last = PeopleMedia.ProfileEdit.lastItemEdited;
            var $container = $jq('div[data-key=\'' + last.key + '\'] > div:last-child');
            $container.html(last.data.html());
            if (last.key.indexOf('greeting') >= 0) {
                PeopleMedia.ProfileEdit.ConfigureGreetingLengths();
            }
            if (last.key.indexOf('miniessay') >= 0) {
                PeopleMedia.ProfileEdit.ConfigureMiniEssayLengths();
            }
            if (last.key == 'Relationship_Expectations') {
                PeopleMedia.ProfileEdit.ConfigureRelationshipCheckboxes();
            } else if (last.data.text().indexOf("Any") >= 0) {
                // Configure all "ANY" checkbox options, this was added with About Your Match questions
                PeopleMedia.ProfileEdit.ConfigureDynamicAnyCheckboxes();
            }

            if (last.key == 'Pet') {
                PeopleMedia.ProfileEdit.ConfigurePetCheckboxes();
            }
            PeopleMedia.ProfileEdit.lastItemEdited = null;
        }
        PeopleMedia.ProfileEdit.HideEditors(e);
    };
    this.HideEditors = function (e) {
        $jq('div.profileedit div.data > div:nth-child(2)').hide();
        $jq('div.profileedit div.data > div:nth-child(1)').removeClass('whiteout').show();

    };
    this.AddResponses = function (responseKeys, responseValues, key, $group) {
        //return  ['string','string'];
        //Check first for checkboxes, then select, then free form text.
        var values = $group.find('input[type="checkbox"]:checked, select, textarea');
        values.each(function () {
            var sel = $jq(this);
            responseKeys.push(key);
            responseValues.push(sel.val());
            
        });
    };
    this.lastItemEdited = null;
    this.messageIdeasInitialItems = [];
    this.CancelMessageIdeas = function (e) {
        e.preventDefault();
        $jq('div.profileedit div.messageideas input[type=checkbox]:checked').each(function () { $jq(this).attr('checked', false); });
        $jq('div.messageideas div.error').hide();
        /*e.preventDefault();
        if (PeopleMedia.ProfileEdit.messageIdeasInitialItems == null) return;
        $jq('div.profileedit div.messageideas input[type=checkbox]').each(function () {
            var item = $jq(this);
            if ($jq.inArray(item.val(), PeopleMedia.ProfileEdit.messageIdeasInitialItems) != -1) {
                item.attr('checked', true);
            } else {
                item.attr('checked', false);
            }
        });
        $jq('div.messageideas div.error').hide();*/

    };
    this.SaveMessageIdeas = function (e) {
      
        e.preventDefault();        
        var $button = $jq(this);
        $button.addClass('saving');
        var responseKeys = [];
        var responseValues = [];
        var key = 'MessageIdeas';
        var $selection = $jq('div.messageideas input[type=checkbox]:checked');
        var responses = $jq.map($selection, function (chkBox) {
            var val = chkBox.getAttribute('value');
            responseKeys.push(key);
            responseValues.push(val);
            return val;
        });
        PeopleMedia.ProfileEdit.messageIdeasInitialItems = responses;
        $jq('div.messageideas div.error').hide();

        var data = { SkipCSSVerif: 'HTMLEditor', QuestionKey: key, ResponseKeys: responseKeys, ResponseValues: responseValues };
        
        $jq.ajax({
            traditional: true,
            url: FRONT_SITE_URL+'user/profile/process',
            type: 'GET',
            data: data,
            success: function (response) {
                var response1 = $jq.parseJSON(response);
                if (response1['Status'] == "Success") {
                    PeopleMedia.Popups.ShowGenericMessage("Your Message Ideas have been saved.");
                } else if (response.Message) {
                    PeopleMedia.Popups.ShowGenericMessage(response.Message);
                }
            },
            complete: function () {
                $button.removeClass('saving');
            }
        });
    };
    this.DeselectMessageIdeas = function (e) {
        e.preventDefault();
        $jq('div.profileedit div.messageideas input[type=checkbox]:checked').each(function () { $jq(this).attr('checked', false); });
        $jq('div.messageideas div.error').hide();
    };
    this.ConfigureDynamicAnyCheckboxes = function () {
        // At the moment (1/15/14 release) we removed "Any" option from Your Match answers, but leaving this in place incase we add it back
        var boxes = $jq('div[data-hasanyresponse=\'True\'] input[type="checkbox"]');
        var anyBox = boxes.filter('[value="-1"]');
        var otherBoxes = boxes.filter('[value!="-1"]');
        
        boxes.off('change');
        if (otherBoxes.length > 0) {
            if (otherBoxes.filter(':checked').length == otherBoxes.length) {
                otherBoxes.attr('checked', false);
            }
            anyBox.attr('checked', otherBoxes.filter(':checked').length == 0);
        }

        otherBoxes.on('change', function () {
            var checked = otherBoxes.filter(':checked').length;
            var total = otherBoxes.length;
            if (checked == total) {
                otherBoxes.attr('checked', false);
            }
            anyBox.attr('checked', otherBoxes.filter(':checked').length == 0);

        });
        anyBox.on('change', function () {
            var checked = anyBox.filter(':checked').length;
            if (checked == 1) {
                otherBoxes.attr('checked', false);
            } else {
                otherBoxes.attr('checked', false);
                anyBox.attr('checked', true);
            }

        });
    };
    this.ConfigureRelationshipCheckboxes = function () {
        var boxes = $jq('div[data-key=\'Relationship_Expectations\'] input[type="checkbox"]');
        var anyBox = boxes.filter('[value="-1"]');
        var otherBoxes = boxes.filter('[value!="-1"]');

        boxes.off('change');
        if (otherBoxes.length > 0) {
            if (otherBoxes.filter(':checked').length == otherBoxes.length) {
                otherBoxes.attr('checked', false);
            }
            anyBox.attr('checked', otherBoxes.filter(':checked').length == 0);
        }

        otherBoxes.on('change', function () {
            var checked = otherBoxes.filter(':checked').length;
            var total = otherBoxes.length;
            if (checked == total) {
                otherBoxes.attr('checked', false);
            }
            anyBox.attr('checked', otherBoxes.filter(':checked').length == 0);

        });
        anyBox.on('change', function () {
            var checked = anyBox.filter(':checked').length;
            if (checked == 1) {
                otherBoxes.attr('checked', false);
            } else {
                otherBoxes.attr('checked', false);
                anyBox.attr('checked', true);
            }

        });
    };
    this.ConfigurePetCheckboxes = function () {
        var boxes = $jq('div[data-key=\'Pet\'] input[type="checkbox"]');
        var noneBox = boxes.filter('[value="65536"]');
        var otherBoxes = boxes.filter('[value!="65536"]');

        boxes.off('change');
        if (otherBoxes.length > 0) {
            noneBox.attr('checked', otherBoxes.filter(':checked').length == 0);
        }

        otherBoxes.on('change', function () {
            var checked = otherBoxes.filter(':checked').length;
            var total = otherBoxes.length;
            noneBox.attr('checked', otherBoxes.filter(':checked').length == 0);

        });
        noneBox.on('change', function () {
            var checked = noneBox.filter(':checked').length;
            if (checked == 1) {
                otherBoxes.attr('checked', false);
            } else {
                otherBoxes.attr('checked', false);
                noneBox.attr('checked', true);
            }

        });
    };
    this.ToggleGreetingHighlight = function (key) {
        var $highlight = $jq('div.highlight[data-key=\'' + key + '\']');
        var $link = $jq('div.data[data-key=\'' + key + '\'] > div:first-child');
        if ($jq('div[data-responsegroup-key=\'' + key + '\'] textarea').val() == "") {
            $highlight.fadeIn('fast');
            $link.addClass('getStarted');
        }
        else {
            $highlight.fadeOut('fast');
            $link.removeClass('getStarted');
        }
    };
};
$jq(document).ready(PeopleMedia.ProfileEdit.init);